package com.topteam.frame.controllor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.topteam.component.easyui.EasyDataTableModel;
import com.topteam.component.easyui.EasyTreeModel;
import com.topteam.component.easyui.EasyTreeNode;
import com.topteam.component.freemarker.SelectItem;
import com.topteam.core.Path;
import com.topteam.frame.entity.FrameDept;
import com.topteam.frame.entity.FrameDeptDuty;
import com.topteam.frame.entity.FrameRole;
import com.topteam.frame.entity.FrameRoleType;
import com.topteam.frame.entity.FrameUserExt;
import com.topteam.frame.entity.UserDeptRelation;
import com.topteam.frame.entity.UserRoleRelation;
import com.topteam.security.UserSession;
import com.topteam.utility.StringUtil;


@Path("/frameuserconfig")
public class FrameUserConfigController extends BaseController {

	public void index() {

		UserSession userSession = getUserSession();
		FrameUserExt userExt = FrameUserExt.dao.getUserExtByUserId(userSession
				.getUserid());
		if (userExt == null) {
			userExt = FrameUserExt.dao.initUserExt(userSession.getUserid());
		}
		setAttr("userExt", userExt);
		
		render("/frame/FrameUserConfig.html");
	}

	public void save() {
		FrameUserExt userExt = getModel(FrameUserExt.class, "userExt");
		userExt.update();
		renderText("保存成功");
	}

	public void addUserDept() {
		int ismain = getParaToInt("ismain");
		String userid = getPara("userid");
		String deptid = getPara("deptid");
		String dutyid = getPara("dutyid");
		UserDeptRelation relation = UserDeptRelation.dao.getUserDeptRelation(
				userid, deptid);
		if (relation != null) {
			renderText("已设置该部门，如要修改请删除后，再设置");
			return;
		}
		UserDeptRelation userDeptRelation = new UserDeptRelation();
		userDeptRelation.set("id", UUID.randomUUID().toString());
		userDeptRelation.set("userid", userid);
		userDeptRelation.set("deptid", deptid);
		userDeptRelation.set("dutyid", dutyid);
		userDeptRelation.set("order", 0);
		userDeptRelation.set("isMainOu", ismain);
		userDeptRelation.save();
		renderText("添加成功");
	}
	
	public void deleteDept(){
		String id = getPara("id");
		if(StringUtil.isNotNull(id))
			UserDeptRelation.dao.deleteById(id);
		renderText("success");
	}
	
	public void myOu() {
		EasyDataTableModel model = new EasyDataTableModel() {
			@Override
			public Page fechData() {
				String userid = getPara("id");
				int isMain = getParaToInt("isMain");
				System.out.println(userid);
				Page p = null;
				p = UserDeptRelation.dao.getUserDeptRelationByUser(userid, isMain);
				return p;
			}
		};
		renderJson(model.toJson());
	}

	
	public void deptDutyTree(){
		EasyTreeModel model = new EasyTreeModel(this) {
			@Override
			public List fechDate(String id) {
				
				List olist = new ArrayList();
				
				List<FrameDeptDuty> dutylist = FrameDeptDuty.dao.find("select *, 0 as has from FrameDeptDuty where deptId=?",id);
				
				List<FrameDept> list = new ArrayList<FrameDept>();
				if(id == null){
					String sql = "select t.*, case when (SELECT count(1) from FrameDept t2 where t2.parentId=t.id)>0 then 1 ELSE 0 END as has, case when (SELECT count(1) from FrameDeptDuty dd where dd.deptId=t.id)>0 then 1 ELSE 0 END as hasDD  from FrameDept t where t.parentId is null order by t.order desc";
					list = FrameDept.dao.find(sql);
				}
				else{
					String sql = "select t.*, case when (SELECT count(1) from FrameDept t2 where t2.parentId=t.id)>0 then 1 ELSE 0 END as has, case when (SELECT count(1) from FrameDeptDuty dd where dd.deptId=t.id)>0 then 1 ELSE 0 END as hasDD from FrameDept t where t.parentId=? order by t.order desc";
					list = FrameDept.dao.find(sql,id);
				}
				
				olist.addAll(dutylist);
				olist.addAll(list);
				return olist;
			}

			@Override
			public EasyTreeNode model2Node(Object t) {
				EasyTreeNode node = new EasyTreeNode();
				if(t instanceof FrameDept){
					FrameDept dept = (FrameDept) t;
					node.setId(dept.getStr("id"));
					node.setText(dept.getStr("deptName"));
					Map<String, String> map = new HashMap<String, String>();
					map.put("deptId", dept.getStr("id"));
					map.put("isreal", dept.getInt("isreal").toString());
					map.put("type", "dept");
					node.setAttributes(map);
					boolean hasChild = dept.getLong("has")>0L||dept.getLong("hasDD")>0L;
					node.setHasChild(hasChild);
				}else if(t instanceof FrameDeptDuty){
					FrameDeptDuty duty = (FrameDeptDuty) t;
					node.setId(duty.getStr("id"));
					node.setText(duty.getStr("dutyName"));
					node.setIconCls("icon-user");
					Map<String, String> map = new HashMap<String, String>();
					map.put("deptId", duty.getStr("deptId"));
					map.put("dutyId", duty.getStr("id"));
					map.put("isreal", "1");
					map.put("type", "duty");
					node.setAttributes(map);
					node.setHasChild(duty.getLong("has")>0L);
				}
				return node;
			}

		};
		
		renderJson(model.toJson());
	}
	
	public void extcfg() {
		setAttr("userId", getPara("id"));
		List<FrameRoleType> list = FrameRoleType.dao.getAllRoleTypeNoPaginate();
		setAttr("types", list);
		render("/frame/FrameUserExtConfig.html");
	}
	
	public void roles(){
		String id = getPara("id");
		String userId = getPara("userId");
		List<FrameRole> list = FrameRole.dao.getRolesByTypeId(id);
		List<SelectItem> items = new ArrayList<SelectItem>();
		List<UserRoleRelation> urrList = UserRoleRelation.dao.getUserRoleRelationByUserId(userId);
		for(FrameRole r : list){
			boolean select = false;
			for(UserRoleRelation urr:urrList){
				if(urr.getStr("roleId").equals(r.getStr("id"))){
					select = true;
					break;
				}
			}
			items.add(new SelectItem(r.getStr("roleName"),r.getStr("id"),select));
		}
		renderJson(items);
	}
	
	public void saveUserRole(){
		String checkRoles = getPara("checkedRoles");
		String userId = getPara("userId");
		String[] roles =checkRoles.split(",");
		UserRoleRelation.dao.deleteUserRoleRelationByUserId(userId);
		for(String r:roles){
			if(StringUtil.isNotNull(r)){
				UserRoleRelation urr = new UserRoleRelation();
				urr.set("id", UUID.randomUUID().toString());
				urr.set("roleId", r);
				urr.set("userId", userId);
				urr.save();
			}
		}
		System.out.println(checkRoles);
		renderText("保存成功");
	}
	
}
